﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Data;
using Ccit.Utils;
using Ccit.SysPlat.Log;
using Ccit.ClassLibrary;

namespace Ccit.SysPlat.Organ
{
    /// <summary>
    /// Description: 系统平台组织机构 -> 用户管理SQL SERVER数据实现层
    /// Author: tim 2010-02-10
    /// </summary>
    public class UserSQL : IUser
    {
        #region init error log interface
        private ILog _logInterface = null;
        private const string _funcPageName = "用户管理";
        public UserSQL()
        {
            _logInterface = Factory.CreateObject(MsErrLog.assemblyName, MsErrLog.className, 
                                                    ImportComponentType.DotNetDll, null) as ILog;
        }        
        #endregion

        #region IUser 成员

        public MsUser GetUserInfo(string userId, eTrueFalse enContainExtend)
        {
            StringBuilder sbCmdText = new StringBuilder();            
            if (enContainExtend == eTrueFalse.TRUE)
            {
                sbCmdText.Append("SELECT A.SYS_A1_10 AS USERID,A.SYS_A1_20 AS LOGINNAME,A.SYS_A1_40 AS USERNAME,A.SYS_A1_50 AS USERCODE,");
                sbCmdText.Append("A.SYS_A1_60 AS UKEFFECT,A.SYS_A1_70 AS UKCODE,A.SYS_A1_80 AS ORDERNO,A.SYS_A1_90 AS EFFECT,");
                sbCmdText.Append("K.SYS_A4_10 AS ORGANID,K.SYS_A4_20 AS ORGANNAME,B.SYS_A2_10 AS DEPTID,B.SYS_A2_20 AS DEPTNAME,C.SYS_A3_10 AS POSID,");
                sbCmdText.Append("C.SYS_A3_20 AS POSNAME,D.SYS_A5_10 AS CLASSID,D.SYS_A5_20 AS CLASSNAME FROM SYS_A1 A ");
                sbCmdText.Append("LEFT JOIN SYS_R1 E ON A.SYS_A1_10=E.SYS_R1_10 LEFT JOIN SYS_A2 B ON B.SYS_A2_10=E.SYS_R1_20 ");
                sbCmdText.Append("LEFT JOIN SYS_R2 F ON A.SYS_A1_10=F.SYS_R2_10 LEFT JOIN SYS_A3 C ON C.SYS_A3_10=F.SYS_R2_20 ");
                sbCmdText.Append("LEFT JOIN SYS_R8 G ON A.SYS_A1_10=G.SYS_R8_10 LEFT JOIN SYS_A5 D ON D.SYS_A5_10=G.SYS_R8_20 ");
                sbCmdText.Append("LEFT JOIN SYS_R3 H ON A.SYS_A1_10=H.SYS_R3_10 LEFT JOIN SYS_A4 K ON K.SYS_A4_10=H.SYS_R3_20 ");
                sbCmdText.Append("WHERE A.SYS_A1_10 ='").Append(userId).Append("'");
            }
            else
            {
                sbCmdText.Append("SELECT A.SYS_A1_10 AS USERID,A.SYS_A1_20 AS LOGINNAME,A.SYS_A1_40 AS USERNAME,A.SYS_A1_50 AS USERCODE,");
                sbCmdText.Append("A.SYS_A1_60 AS UKEFFECT,A.SYS_A1_70 AS UKCODE,A.SYS_A1_80 AS ORDERNO,A.SYS_A1_90 AS EFFECT ");
                sbCmdText.Append("FROM SYS_A1 A WHERE A.SYS_A1_10='").Append(userId).Append("'");
            }

            MsUser msUser = null;
            try {
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    if (iReader.Read() && null != iReader[0])
                    {
                        msUser = new MsUser {
                            userId = iReader["USERID"].ToString(),
                            loginName = iReader["LOGINNAME"].ToString(),
                            userName = iReader["USERNAME"].ToString(),
                            userCode = iReader["USERCODE"].ToString(),
                            ePassSign = (eTrueFalse)Enum.Parse(typeof(eTrueFalse),iReader["UKEFFECT"].ToString()),
                            ePass = iReader["UKCODE"].ToString(),
                            orderNo = iReader["ORDERNO"].ToString(),
                            delSign = (eTrueFalse)Enum.Parse(typeof(eTrueFalse), iReader["EFFECT"].ToString()),                            
                            belongOrgan = (enContainExtend == eTrueFalse.TRUE) ? new MsOrgan {
                                organId = iReader["ORGANID"].ToString(),
                                organName = iReader["ORGANNAME"].ToString()
                            } : null,
                            belongDept = (enContainExtend == eTrueFalse.TRUE) ? new MsDept {
                                deptId = iReader["DEPTID"].ToString(),
                                deptName = iReader["DEPTNAME"].ToString()
                            } : null,
                            belongPos = (enContainExtend == eTrueFalse.TRUE) ? new MsPos {
                                posId = iReader["POSID"].ToString(),
                                posName = iReader["POSNAME"].ToString()
                            } : null,
                            belongClass = (enContainExtend == eTrueFalse.TRUE) ? new MsClass {
                                clsId = iReader["CLASSID"].ToString(),
                                clsName = iReader["CLASSNAME"].ToString()
                            } : null
                        };
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;               
            }

            sbCmdText = null;
            return msUser;
        }

        public DataSet GetUserList(MsUser whereClause)
        {
            StringBuilder sbCmdText = new StringBuilder();
            string qryCon = " 1=1 ";
            string organId = (null != whereClause && null != whereClause.belongOrgan) ? whereClause.belongOrgan.organId : string.Empty;
            string delSign = (null != whereClause) ? whereClause.delSign.ToString("D") : string.Empty;

            if (!string.IsNullOrEmpty(organId))
                qryCon += "AND K.SYS_A4_10='" + organId + "' ";

            if (!string.IsNullOrEmpty(delSign))
                qryCon += "AND A.SYS_A1_90='" + delSign + "' ";

            sbCmdText.Append("SELECT A.SYS_A1_10 AS USERID,A.SYS_A1_20 AS LOGINNAME,A.SYS_A1_40 AS USERNAME,A.SYS_A1_50 AS USERCODE,");
            sbCmdText.Append("A.SYS_A1_80 AS ORDERNO,A.SYS_A1_90 AS DELSIGN,B.SYS_A2_10 AS DEPTID,B.SYS_A2_20 AS DEPTNAME,C.SYS_A3_10 AS POSID,");
            sbCmdText.Append("C.SYS_A3_20 AS POSNAME,D.SYS_A5_10 AS CLASSID,D.SYS_A5_20 AS CLASSNAME FROM SYS_A1 A ");
            sbCmdText.Append("LEFT JOIN SYS_R1 E ON A.SYS_A1_10=E.SYS_R1_10 LEFT JOIN SYS_A2 B ON B.SYS_A2_10=E.SYS_R1_20 ");
            sbCmdText.Append("LEFT JOIN SYS_R2 F ON A.SYS_A1_10=F.SYS_R2_10 LEFT JOIN SYS_A3 C ON C.SYS_A3_10=F.SYS_R2_20 ");
            sbCmdText.Append("LEFT JOIN SYS_R8 G ON A.SYS_A1_10=G.SYS_R8_10 LEFT JOIN SYS_A5 D ON D.SYS_A5_10=G.SYS_R8_20 ");
            sbCmdText.Append("LEFT JOIN SYS_R3 H ON A.SYS_A1_10=H.SYS_R3_10 LEFT JOIN SYS_A4 K ON K.SYS_A4_10=H.SYS_R3_20 ");
            sbCmdText.Append("WHERE ").Append(qryCon);
            sbCmdText.Append("ORDER BY A.SYS_A1_80 ASC");

            DataSet dSet = null;            
            try {
                dSet = DataAccessor.ExecuteDataSet(sbCmdText.ToString());
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            sbCmdText = null;
            return dSet;            
        }

        public List<string> Delete(string userIds)
        {
            string cmdText = "UPDATE SYS_A1 SET SYS_A1_90='1' WHERE SYS_A1_10 IN (" + userIds + ")";

            try {
                int iexe = DataAccessor.ExecuteNonQuery(cmdText);
                if (iexe > 0) return new List<string> { "1", "删除成功!" };
                else return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }
        }

        public List<string> Resume(string userIds)
        {
            string cmdText = "UPDATE SYS_A1 SET SYS_A1_90='0' WHERE SYS_A1_10 IN (" + userIds + ")";

            try {
                int iexe = DataAccessor.ExecuteNonQuery(cmdText);
                if (iexe > 0) return new List<string> { "1", "恢复成功!" };
                else return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }
        }

        public List<string> ResumeDefPwd(string userIds)
        {
            string defPwd = getDefPwd();
            string cmdText = "UPDATE SYS_A1 SET SYS_A1_30='" + defPwd + "' WHERE SYS_A1_10 IN (" + userIds + ")";

            try {
                int iexe = DataAccessor.ExecuteNonQuery(cmdText);
                if (iexe > 0) return new List<string> { "1", "恢复成功!" };
                else return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }
        }

        public List<string> MoveDown(string userId, string curOrder)
        {
            return singleMoveOrder("DOWN", userId, curOrder);
        }

        public List<string> MoveUp(string userId, string curOrder)
        {
            return singleMoveOrder("UP", userId, curOrder);
        }

        public List<MsKeyValue> GetUserListByIds(string userIds,string findUserName)
        {
            if(string.IsNullOrEmpty(userIds)) return new List<MsKeyValue>();

            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT SYS_A1_10 AS USERID,SYS_A1_40 AS USERNAME FROM SYS_A1 ");
            sbCmdText.Append("WHERE SYS_A1_10 IN (").Append(userIds).Append(")");

            if (!string.IsNullOrEmpty(findUserName))
                sbCmdText.Append(" AND SYS_A1_40 LIKE '%").Append(findUserName).Append("%'");

            List<MsKeyValue> lstUser = new List<MsKeyValue>();
            try {
                MsKeyValue msUser;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        msUser = new MsKeyValue {
                            key = iReader["USERID"].ToString(),
                            val = iReader["USERNAME"].ToString()
                        };
                        lstUser.Add(msUser);
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;       
            }

            sbCmdText = null;
            return lstUser;
        }

        public List<MsKeyValue> GetUserListByOrgan(string organId, string filterUserIds, eTrueFalse enEffect)
        {
            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT A.SYS_A1_10 AS USERID,A.SYS_A1_40 AS USERNAME FROM SYS_A1 A ");
            sbCmdText.Append("INNER JOIN SYS_R3 B ON A.SYS_A1_10=B.SYS_R3_10 ");
            sbCmdText.Append("WHERE B.SYS_R3_20='").Append(organId).Append("' AND A.SYS_A1_90='").Append(enEffect.ToString("D")).Append("' ");
            if(!string.IsNullOrEmpty(filterUserIds))
                sbCmdText.Append("AND A.SYS_A1_10 NOT IN (").Append(filterUserIds).Append(")");
            sbCmdText.Append("ORDER BY A.SYS_A1_80 ASC");

            List<MsKeyValue> lstUser = new List<MsKeyValue>();
            try {
                MsKeyValue msUser;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        msUser = new MsKeyValue {
                            key = iReader["USERID"].ToString(),
                            val = iReader["USERNAME"].ToString()
                        };
                        lstUser.Add(msUser);
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;               
            }

            sbCmdText = null;
            return lstUser;
        }

        public List<MsKeyValue> GetUserListByOrgan(string organId, eTrueFalse enEffect, string whereClause)
        {
            StringBuilder sbCmdText = new StringBuilder();
            sbCmdText.Append("SELECT A.SYS_A1_10 AS USERID,A.SYS_A1_40 AS USERNAME FROM SYS_A1 A ");
            sbCmdText.Append("LEFT JOIN SYS_R1 E ON A.SYS_A1_10=E.SYS_R1_10 LEFT JOIN SYS_A2 B ON B.SYS_A2_10=E.SYS_R1_20 ");
            sbCmdText.Append("LEFT JOIN SYS_R2 F ON A.SYS_A1_10=F.SYS_R2_10 LEFT JOIN SYS_A3 C ON C.SYS_A3_10=F.SYS_R2_20 ");
            sbCmdText.Append("LEFT JOIN SYS_R8 G ON A.SYS_A1_10=G.SYS_R8_10 LEFT JOIN SYS_A5 D ON D.SYS_A5_10=G.SYS_R8_20 ");
            sbCmdText.Append("LEFT JOIN SYS_R3 H ON A.SYS_A1_10=H.SYS_R3_10 LEFT JOIN SYS_A4 K ON K.SYS_A4_10=H.SYS_R3_20 ");
            sbCmdText.Append("WHERE K.SYS_A4_10='").Append(organId).Append("' AND A.SYS_A1_90='").Append(enEffect.ToString("D")).Append("' ");
            sbCmdText.Append("AND ").Append(whereClause).Append("ORDER BY A.SYS_A1_80 ASC");


            List<MsKeyValue> lstUser = new List<MsKeyValue>();
            try {
                MsKeyValue msUser;
                using (IDataReader iReader = DataAccessor.ExecuteReader(sbCmdText.ToString()))
                {
                    while (iReader.Read())
                    {
                        msUser = new MsKeyValue
                        {
                            key = iReader["USERID"].ToString(),
                            val = iReader["USERNAME"].ToString()
                        };
                        lstUser.Add(msUser);
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + sbCmdText.ToString() + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }

            sbCmdText = null;
            return lstUser;
        }

        public string GetUserNamesByIds(string userIds, string separator)
        {
            string cmdText = "SELECT SYS_A1_40 AS USERNAME FROM SYS_A1 WHERE SYS_A1_10 IN (" + userIds + ")";
            string userNames = string.Empty;
            string userName = string.Empty;
            
            try {
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        userName = iReader["USERNAME"].ToString();
                        userNames += (string.IsNullOrEmpty(userNames)) ? userName : separator + userName;
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
            }
            return userNames;
        }
        
        public string GetUserNamesByIds(string userIds, string separator, eTrueFalse isFilter)
        {
            if (string.IsNullOrEmpty(userIds)) return string.Empty;

            string userNames = string.Empty;
            if (isFilter == eTrueFalse.TRUE)
            {
                string cmdText = "SELECT SYS_A1_40 AS USERNAME FROM SYS_A1 WHERE SYS_A1_10 IN (" + userIds + ") AND SYS_A1_90='0'";
                try
                {
                    string userName = string.Empty;                    
                    using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                    {
                        while (iReader.Read())
                        {
                            userName = iReader["USERNAME"].ToString();
                            userNames += (string.IsNullOrEmpty(userNames)) ? userName : separator + userName;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MsErrLog msErrorLog = new MsErrLog
                    {
                        funcPageName = _funcPageName,
                        errMsg = ex.Message,
                        codeTrack = ex.StackTrace,
                        errClassCode = "001", //SQL 异常
                        paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                    };

                    _logInterface.WriteErrorLog(msErrorLog);
                    msErrorLog = null;
                }
            }
            else
            {
                userNames = GetUserNamesByIds(userIds, separator);
            }
            return userNames;
        }
        
        public List<string> Save(MsUser msUser)
        {
            string userId = msUser.userId;
            List<string> lstResult = null;
            if (string.IsNullOrEmpty(userId))
                lstResult = addnew(msUser);
            else
                lstResult = update(msUser);

            return lstResult;
        }
        
        public string GetOnlineData(string userId)
        {
            string cmdText = "select * from v_udp where onlinesign=1";
            StringBuilder sb = new StringBuilder("<PLATEDATA>");
            DataSet dSet = null;
            string pageParam = string.Empty;
            string encodeParam = string.Empty;
            dSet = DataAccessor.ExecuteDataSet(cmdText);
            if (dSet != null)
            {
                int iCount = dSet.Tables[0].Rows.Count;
                sb.Append("<SHOWTOTAL>0</SHOWTOTAL>");
                sb.Append("<TOTAL>").Append(iCount).Append("</TOTAL>");
               
                //pageParam = "PageSource=6";
                //encodeParam = Base64Lib.Encode(pageParam);
                string moreAddr = "msg/msg_send_edit.aspx";
                sb.Append("<MOREADDRESS MODTYPEID='' MODMENUID='' LEAFMENUID=''>").Append(moreAddr).Append("</MOREADDRESS>");
                sb.Append("<POPMODE>2</POPMODE>");
                sb.Append("<RECORDS>");
                for (int i = 0; i < iCount; i++)
                {
                    string sUserName = dSet.Tables[0].Rows[i]["USERNAME"].ToString();
                    string sUserId = dSet.Tables[0].Rows[i]["USERID"].ToString();
                    pageParam = "RecevierId=" + sUserId + "&PageSource=4";
                    encodeParam = Base64Lib.Encode(pageParam);
                    string strUrl = "./msg/msg_receive_back.aspx?" + encodeParam;
                    sb.Append("<RECORD><TITLE><![CDATA[").Append(sUserName).Append("]]></TITLE>");
                    sb.Append("<LINKADDRESS><![CDATA[").Append(strUrl).Append("]]></LINKADDRESS></RECORD>");
                }
                sb.Append("</RECORDS>");
            }
            sb.Append("</PLATEDATA>");
            return sb.ToString(); 
        }

        public List<string> SetUserOnlineStatus(MsLoginUser loginUser, string status)
        {
            List<string> lstResult = new List<string>();
            if (null == loginUser)
            {
                lstResult.Add("-999");
                lstResult.Add("操作失败:缺少必要参数!");
                return lstResult;
            }

            string cmdText = string.Empty;
            StringBuilder sbCmdText = new StringBuilder();

            string recId = string.Empty;
            cmdText = "SELECT SYS_O1_10 FROM SYS_O1 WHERE SYS_O1_20='" + loginUser.userId + "' AND SYS_O1_30='" + loginUser.userType.ToString("D") +
                      "' AND SYS_O1_40='" + loginUser.organId + "'";
            using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
            {
                if (iReader.Read() && null != iReader[0])
                {
                    recId = iReader["SYS_O1_10"].ToString();
                }
            }


            if (string.IsNullOrEmpty(recId))
            {
                int newRecId = DataInterface.GetMaxId("SYS_O1", "SYS_O1_10");
                sbCmdText.Append("INSERT INTO SYS_O1(SYS_O1_10,SYS_O1_20,SYS_O1_30,SYS_O1_40,SYS_O1_50,SYS_O1_60,SYS_O1_70) VALUES (");
                sbCmdText.Append("'").Append(newRecId.ToString()).Append("',");
                sbCmdText.Append("'").Append(loginUser.userId).Append("',");
                sbCmdText.Append("'").Append(loginUser.userType.ToString("D")).Append("',");
                sbCmdText.Append("'").Append(loginUser.organId).Append("',");
                sbCmdText.Append("'',");
                sbCmdText.Append("'',");
                sbCmdText.Append("'1')");
            }
            else
            {
                sbCmdText.Append("UPDATE SYS_O1 SET SYS_O1_70='").Append(status).Append("' WHERE SYS_O1_10='").Append(recId).Append("'");
            }

            int iexe = DataAccessor.ExecuteNonQuery(sbCmdText.ToString());
            if (iexe > 0)
            {
                lstResult.Add("1");
                lstResult.Add("状态设置成功!");
            }
            else
            {
                lstResult.Add("-1");
                lstResult.Add("操作失败:服务器忙,请稍后再试!");
            }

            sbCmdText.Remove(0, sbCmdText.ToString().Length);
            sbCmdText = null;
            return lstResult;
        }

        public List<string> CheckUserPwd(string userId, eUserType enUserType, string oriPwd)
        {
            string cmdText = string.Empty;
            if (enUserType.Equals(eUserType.ORDINARY))
                cmdText = "SELECT SYS_A1_10 AS USERID,SYS_A1_30 AS PWD FROM SYS_A1 WHERE SYS_A1_10='" + userId + "'";
            else
                cmdText = "SELECT SYS_A6_10 AS USERID,SYS_A6_30 AS PWD FROM SYS_A6 WHERE SYS_A6_10='" + userId + "'";

            try
            {
                string recPwd = string.Empty;                
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    if (iReader.Read() && null != iReader[0])
                        recPwd = iReader["PWD"].ToString();
                }


                string encryptPwd = MD5Lib.Encrypt(oriPwd);
                if (recPwd.Equals(encryptPwd)) return new List<string> { "1", "口令正确!" };
                else return new List<string> { "-1", "原始口令输入不正确!" };
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                return new List<string> { "-2", "操作失败:详情请参见错误日志!" };
            }
        }

        public List<string> ModifyPwd(string userId, eUserType enUserType, string newPwd)
        {
            string cmdText = string.Empty;
            string encryptPwd = MD5Lib.Encrypt(newPwd);
            if (enUserType.Equals(eUserType.ORDINARY))
                cmdText = "UPDATE SYS_A1 SET SYS_A1_30='" + encryptPwd + "' WHERE SYS_A1_10='" + userId + "'";
            else
                cmdText = "UPDATE SYS_A6 SET SYS_A6_30='" + encryptPwd + "' WHERE SYS_A6_10='" + userId + "'";

            try
            {
                int iexe = DataAccessor.ExecuteNonQuery(cmdText);
                if (iexe > 0) return new List<string> { "1", "修改成功!" };
                else return new List<string> { "-1", "操作失败:服务器忙请稍后再试!" };
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                return new List<string> { "-2", "操作失败:详情请参见错误日志!" };
            }
        }
        #endregion

        #region private methods

        private string getDefPwd()
        {
            string oriPwd = "kkkkkk";
            return MD5Lib.Encrypt(oriPwd);
        }

        /// <summary>
        /// 单步移动用户显示顺序
        /// </summary>
        /// <param name="moveType">移动类型:【UP】:上移 【DOWN】:下移</param>
        /// <param name="userId">用户Id</param>
        /// <param name="curOrder">用户当前显示顺序</param>
        /// <returns></returns>
        private List<string> singleMoveOrder(string moveType,string userId,string curOrder)
        {
            string orderMode = (moveType.ToUpper().Equals("UP")) ? "ASC" : "DESC";
            string cmdText = "SELECT SYS_A1_10 AS USERID,SYS_A1_80 AS ORDERNO FROM SYS_A1 ORDER BY SYS_A1_80 " + orderMode;
            string userRecId = string.Empty;
            string recOrder = string.Empty;

            string excRecId = string.Empty;
            string excOrder = string.Empty;

            try
            {
                using (IDataReader iReader = DataAccessor.ExecuteReader(cmdText))
                {
                    while (iReader.Read())
                    {
                        userRecId = iReader["USERID"].ToString();
                        recOrder = iReader["ORDERNO"].ToString();

                        if (userRecId.Equals(userId)) break;

                        excRecId = userRecId;
                        excOrder = recOrder;
                    }
                }
            }
            catch (Exception ex)
            {
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = "<SQL><![CDATA[" + cmdText + "]]></SQL>"
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }

            if (string.IsNullOrEmpty(excRecId)) return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            else
            {
                List<string> lstCmdText = new List<string>();
                cmdText = "UPDATE SYS_A1 SET SYS_A1_80=" + excOrder + " WHERE SYS_A1_10='" + userId + "'";
                lstCmdText.Add(cmdText);
                cmdText = "UPDATE SYS_A1 SET SYS_A1_80=" + curOrder + " WHERE SYS_A1_10='" + excRecId + "'";
                lstCmdText.Add(cmdText);

                try
                {
                    int iexe = DataAccessor.ExecuteNonQuery(lstCmdText);
                    if (iexe > 0) return new List<string> { "1", "调整成功!" };
                    else return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
                }
                catch (Exception ex)
                {
                    #region 记录错误日志
                    StringBuilder sbParam = new StringBuilder();
                    int sqlIndex = 1;
                    foreach (string eSQL in lstCmdText)
                    {
                        sbParam.Append("<SQL" + sqlIndex.ToString()).Append("><![CDATA[").Append(eSQL);
                        sbParam.Append("]]></SQL" + sqlIndex.ToString() + ">");
                        sqlIndex++;
                    }
                    MsErrLog msErrorLog = new MsErrLog
                    {
                        funcPageName = _funcPageName,
                        errMsg = ex.Message,
                        codeTrack = ex.StackTrace,
                        errClassCode = "001", //SQL 异常
                        paramInfo = sbParam.ToString()
                    };

                    _logInterface.WriteErrorLog(msErrorLog);
                    msErrorLog = null;
                    sbParam = null;
                    return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
                    #endregion
                }

            }
        }

        /// <summary>
        /// 新增用户记录
        /// </summary>
        /// <param name="msUser"></param>
        /// <returns>
        ///     【0】: 操作标志位 newRecId / 负数
        ///     【1】: 操作提示消息
        /// </returns>
        private List<string> addnew(MsUser msUser)
        {            
            List<string> lstCmdText = new List<string>();
            StringBuilder sbCmdText = new StringBuilder();
            string cmdText = string.Empty;

            #region 添加用户记录
            sbCmdText.Append("INSERT INTO SYS_A1 (SYS_A1_10,SYS_A1_20,SYS_A1_30,SYS_A1_40,SYS_A1_50,SYS_A1_60,SYS_A1_70,SYS_A1_80,");
            sbCmdText.Append("SYS_A1_90) VALUES (");
            int orderNo = DataInterface.GetMaxId("SYS_A1", "SYS_A1_80");
            int newRecId = DataInterface.GetMaxId("SYS_A1", "SYS_A1_10");
            if (orderNo == 0 || newRecId == 0) return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            sbCmdText.Append("'").Append(newRecId.ToString()).Append("',");
            sbCmdText.Append("'").Append(msUser.loginName.Replace("'", "''")).Append("',");
            sbCmdText.Append("'").Append(getDefPwd()).Append("',");
            sbCmdText.Append("'").Append(msUser.userName.Replace("'", "''")).Append("',");
            sbCmdText.Append("'").Append(msUser.userCode.Replace("'", "''")).Append("',");
            sbCmdText.Append("'").Append(msUser.ePassSign.ToString("D")).Append("',");
            sbCmdText.Append("'").Append(msUser.ePass.Replace("'","''")).Append("',");
            sbCmdText.Append("'").Append(orderNo.ToString()).Append("','0')");
            lstCmdText.Add(sbCmdText.ToString());
            sbCmdText.Remove(0, sbCmdText.ToString().Length);
            #endregion

            #region 保存关系信息
            string organId = (null != msUser.belongOrgan) ? msUser.belongOrgan.organId : string.Empty;
            string deptId = (null != msUser.belongDept) ? msUser.belongDept.deptId : string.Empty;
            string posId = (null != msUser.belongPos) ? msUser.belongPos.posId : string.Empty;
            string clsId = (null != msUser.belongClass) ? msUser.belongClass.clsId : string.Empty;

            if (!string.IsNullOrEmpty(organId))
            {
                sbCmdText.Append("INSERT INTO SYS_R3(SYS_R3_10,SYS_R3_20) VALUES(");
                sbCmdText.Append("'").Append(newRecId.ToString()).Append("','").Append(organId).Append("')");
                lstCmdText.Add(sbCmdText.ToString());
                sbCmdText.Remove(0, sbCmdText.ToString().Length);
            }

            if (!string.IsNullOrEmpty(deptId))
            {
                string[] deptArray = deptId.Split(',');
                foreach(string eDeptId in deptArray)
                {
                    sbCmdText.Append("INSERT INTO SYS_R1(SYS_R1_10,SYS_R1_20,SYS_R1_30) VALUES(");
                    sbCmdText.Append("'").Append(newRecId.ToString()).Append("','").Append(eDeptId).Append("','0')");
                    lstCmdText.Add(sbCmdText.ToString());
                    sbCmdText.Remove(0, sbCmdText.ToString().Length);
                }
            }

            if (!string.IsNullOrEmpty(posId))
            {
                string[] posArray = posId.Split(',');
                foreach (string ePosId in posArray)
                {
                    sbCmdText.Append("INSERT INTO SYS_R2(SYS_R2_10,SYS_R2_20,SYS_R2_30) VALUES(");
                    sbCmdText.Append("'").Append(newRecId.ToString()).Append("','").Append(ePosId).Append("','0')");
                    lstCmdText.Add(sbCmdText.ToString());
                    sbCmdText.Remove(0, sbCmdText.ToString().Length);
                }
            }

            if (!string.IsNullOrEmpty(clsId))
            {
                sbCmdText.Append("INSERT INTO SYS_R8(SYS_R8_10,SYS_R8_20) VALUES(");
                sbCmdText.Append("'").Append(newRecId.ToString()).Append("','").Append(clsId).Append("')");
                lstCmdText.Add(sbCmdText.ToString());
            }
            #endregion

            try {
                int iexe = DataAccessor.ExecuteNonQuery(lstCmdText);
                if (iexe > 0) return new List<string> { newRecId.ToString(), "保存成功!" };
                else return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }
            catch (Exception ex)
            {
                StringBuilder sbParam = new StringBuilder();
                int sqlIndex = 1;
                foreach (string eSQL in lstCmdText)
                {
                    sbParam.Append("<SQL" + sqlIndex.ToString()).Append("><![CDATA[").Append(eSQL);
                    sbParam.Append("]]></SQL" + sqlIndex.ToString() + ">");
                    sqlIndex++;
                }
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = sbParam.ToString()
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                sbParam = null;
                return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }
        }

        /// <summary>
        /// 更新用户记录
        /// </summary>
        /// <param name="msUser"></param>
        /// <returns>
        ///     【0】: 操作标志位 userId / 负数
        ///     【1】: 操作提示消息
        /// </returns>
        private List<string> update(MsUser msUser)
        {
            List<string> lstCmdText = new List<string>();
            StringBuilder sbCmdText = new StringBuilder();
            string cmdText = string.Empty;
            string userId = msUser.userId;

            #region 更新用户记录信息
            sbCmdText.Append("UPDATE SYS_A1 SET SYS_A1_20='").Append(msUser.loginName.Replace("'", "''")).Append("',");
            sbCmdText.Append("SYS_A1_40='").Append(msUser.userName.Replace("'","''")).Append("',");
            sbCmdText.Append("SYS_A1_50='").Append(msUser.userCode.Replace("'", "''")).Append("',");
            sbCmdText.Append("SYS_A1_60='").Append(msUser.ePassSign.ToString("D")).Append("',");
            sbCmdText.Append("SYS_A1_70='").Append(msUser.ePass.Replace("'", "''")).Append("' ");
            sbCmdText.Append("WHERE SYS_A1_10='").Append(userId).Append("'");
            lstCmdText.Add(sbCmdText.ToString());
            sbCmdText.Remove(0, sbCmdText.ToString().Length);
            #endregion

            #region 更新关系信息
            string organId = (null != msUser.belongOrgan) ? msUser.belongOrgan.organId : string.Empty;
            string deptId = (null != msUser.belongDept) ? msUser.belongDept.deptId : string.Empty;
            string posId = (null != msUser.belongPos) ? msUser.belongPos.posId : string.Empty;
            string clsId = (null != msUser.belongClass) ? msUser.belongClass.clsId : string.Empty;

            cmdText = "DELETE FROM SYS_R3 WHERE SYS_R3_10='" + userId + "'";
            lstCmdText.Add(cmdText);
            if (!string.IsNullOrEmpty(organId))
            {
                sbCmdText.Append("INSERT INTO SYS_R3(SYS_R3_10,SYS_R3_20) VALUES(");
                sbCmdText.Append("'").Append(userId).Append("','").Append(organId).Append("')");
                lstCmdText.Add(sbCmdText.ToString());
                sbCmdText.Remove(0, sbCmdText.ToString().Length);
            }

            cmdText = "DELETE FROM SYS_R1 WHERE SYS_R1_10='" + userId + "'";
            lstCmdText.Add(cmdText);
            if (!string.IsNullOrEmpty(deptId))
            {
                string[] deptArray = deptId.Split(',');
                foreach (string eDeptId in deptArray)
                {
                    sbCmdText.Append("INSERT INTO SYS_R1(SYS_R1_10,SYS_R1_20,SYS_R1_30) VALUES(");
                    sbCmdText.Append("'").Append(userId).Append("','").Append(eDeptId).Append("','0')");
                    lstCmdText.Add(sbCmdText.ToString());
                    sbCmdText.Remove(0, sbCmdText.ToString().Length);
                }
            }

            cmdText = "DELETE FROM SYS_R2 WHERE SYS_R2_10='" + userId + "'";
            lstCmdText.Add(cmdText);
            if (!string.IsNullOrEmpty(posId))
            {
                string[] posArray = posId.Split(',');
                foreach (string ePosId in posArray)
                {
                    sbCmdText.Append("INSERT INTO SYS_R2(SYS_R2_10,SYS_R2_20,SYS_R2_30) VALUES(");
                    sbCmdText.Append("'").Append(userId).Append("','").Append(ePosId).Append("','0')");
                    lstCmdText.Add(sbCmdText.ToString());
                    sbCmdText.Remove(0, sbCmdText.ToString().Length);
                }
            }

            cmdText = "DELETE FROM SYS_R8 WHERE SYS_R8_10='" + userId + "'";
            lstCmdText.Add(cmdText);
            if (!string.IsNullOrEmpty(clsId))
            {
                sbCmdText.Append("INSERT INTO SYS_R8(SYS_R8_10,SYS_R8_20) VALUES(");
                sbCmdText.Append("'").Append(userId).Append("','").Append(clsId).Append("')");
                lstCmdText.Add(sbCmdText.ToString());
            }
            #endregion

            try
            {
                int iexe = DataAccessor.ExecuteNonQuery(lstCmdText);
                if (iexe > 0) return new List<string> { userId, "保存成功!" };
                else return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }
            catch (Exception ex)
            {
                StringBuilder sbParam = new StringBuilder();
                int sqlIndex = 1;
                foreach (string eSQL in lstCmdText)
                {
                    sbParam.Append("<SQL" + sqlIndex.ToString()).Append("><![CDATA[").Append(eSQL);
                    sbParam.Append("]]></SQL" + sqlIndex.ToString() + ">");
                    sqlIndex++;
                }
                MsErrLog msErrorLog = new MsErrLog
                {
                    funcPageName = _funcPageName,
                    errMsg = ex.Message,
                    codeTrack = ex.StackTrace,
                    errClassCode = "001", //SQL 异常
                    paramInfo = sbParam.ToString()
                };

                _logInterface.WriteErrorLog(msErrorLog);
                msErrorLog = null;
                sbParam = null;
                return new List<string> { "-1", "操作失败:详情请参见错误日志!" };
            }
        }
        #endregion

    }
        
}
